package tests;

import static org.junit.Assert.*;

import model.impl.ServiceDispatcher;
import model.impl.Task;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class ServiceDispatcherTest
{

	int testValue;
	int prevValue;
	
	@BeforeClass
	public static void setUpBeforeClass() throws Exception
	{
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception
	{
	}

	@Test
	public void TestSynchronized()
	{
		testValue = 0;
		Task t = new Task()
		{
			
			@Override
			public void execute()
			{
				// TODO Auto-generated method stub
				testValue++;
			}			
		};
		
		for(int i = 0; i < 1000; i++)
		{
			ServiceDispatcher.getInstance().enqueue(t);
		}
		
		try
		{
			Thread.sleep(2000);
		} catch (InterruptedException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		assertEquals(1000, testValue);		
	}
	
	@Test
	public void TestOrdering()
	{
		testValue = 1;
		prevValue = 0;
		
		Task t = new Task()
		{
			
			@Override
			public void execute()
			{
				// TODO Auto-generated method stub
				try
				{
					Thread.sleep(50);
					prevValue = testValue;
					testValue++;
					Thread.sleep(50);
				}
				catch (InterruptedException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}				
			}
		};
		
		for( int i = 0; i < 1000; i++ )
		{
			assertEquals(testValue, prevValue+1);
			ServiceDispatcher.getInstance().enqueue(t);
			assertEquals(testValue, prevValue+1);
		}
	}
}
